import React from "react";
import GoBack from "@/components/TheGoBack";
import {
  Button,
  Form,
  Space,
  Cascader,
  Select,
  Image,
  InputNumber,
  Modal,
  message,
} from "antd";
import TheTable from "@/components/TheTable";
import TheButton from "@/components/TheButton";
import _ from "lodash";
import TheList from "./List/index";
import TheUpload from "@/components/TheUpload";
import TheImage from "@/components/TheImage";
import {
  apiGetBrandinfoList,
  apiGetGoodsClassifyTree,
  apiGetAppBrandInfoAdd,
  apiGetAppBrandInfoView,
  apiGetAppBrandInfoUpdate,
} from "@/request/mallManagement";
import store from "@/store/store";

const { Option } = Select;

class Edit extends React.Component {
  constructor(props) {
    super(props);
    this.TheList = React.createRef();
    this.flag = 0;
    this.state = {
      brandId: "",
      brandName: "",
      isModalOpen: false,
      title: "选择商品",
      showUpFile: true,
      fileList: [],
      maxSize: 0.5,
      radioValue: "0",
      typeTitle: "",
      visible: false,
      btnLoading: false,
      brandClassifyIds: "",
      AdID: "",
      brandInfo: {},
      fileType: "image",
      classifyList: [],
      brandList: [],
      isEdit: false,
      initialValues: {
        configCarouselShowType: 0,
        configCarouselUri: "",
        configCarouselType: "0",
      },
      dataSource: [],
      configCarouselUri: "",
      columns: [
        {
          title: "商品ID",
          dataIndex: "goodsId",
          key: "goodsId",
        },
        {
          title: "商品名称",
          dataIndex: "goodsName",
          key: "goodsName",
          render: (text, record) => {
            return (
              <div
                style={{
                  width: 200,
                  overflow: "hidden",
                  whiteSpace: "nowrap",
                  textOverflow: "ellipsis",
                }}
              >
                {record.goodsName}
              </div>
            );
          },
        },
        // {
        //   title: "商品图片",
        //   dataIndex: "goodsShowImages",
        //   key: "goodsShowImages",
        //   render: (text) => {
        //     return (
        //       <Space>{<TheImage src={text} width={80} height={80} />}</Space>
        //     );
        //   },
        // },
        {
          title: "商品图片",
          dataIndex: "goodsShowImages",
          key: "goodsShowImages",
          render: (text) => {
            let arr = text.split(",");
            return (
              <Space>
                {arr.map((v) => {
                  return <TheImage src={v} width={80} height={80} />;
                })}
              </Space>
            );
          },
        },
        {
          title: "所属类目",
          dataIndex: "goodsClassifyName",
          key: "goodsClassifyName",
        },
        {
          title: "商品原价",
          dataIndex: "originalPrice",
          key: "originalPrice",
          render: (text) => {
            return <React.$Price price={text || 0} />;
          },
        },
        {
          title: "商品现价",
          dataIndex: "currentPrice",
          key: "currentPrice",
          render: (text) => {
            return <React.$Price price={text || 0} />;
          },
        },
        {
          title: "上次操作时间",
          dataIndex: "lastUpdateTime",
          key: "lastUpdateTime",
          render: (text, record) => {
            return record.lastUpdateTime ? record.lastUpdateTime : "/";
          },
        },
        {
          title: "状态",
          dataIndex: "goodsStatus",
          key: "goodsStatus",
          render: (text, render) => {
            let label = "";
            switch (render.goodsStatus) {
              case "Y":
                label = "上架";
                break;
              case "N":
                label = "下架";
                break;
              case "G":
                label = "管理员下架";
                break;
              default:
                label = "字段值错误";
            }
            return label;
          },
        },
        {
          title: "操作",
          render: (text, render) => {
            return (
              <>
                <TheButton haspermi={[]} onClick={() => this.del(render)}>
                  删除
                </TheButton>
              </>
            );
          },
        },
      ],
    };
  }

  del = (render) => {
    let arr = this.state.dataSource;
    arr = arr.filter((item) => {
      return item.goodsId != render.goodsId;
    });
    this.setState({
      dataSource: arr,
    });
    this.formRef.setFieldsValue({
      appBrandGoods: arr,
    });
  };
  async componentDidMount() {
    const { id } = this.props.match.params;
    if (id != 0) {
      await this.getData(id);
    }
    this.setState({
      AdID: id,
      showUpFile: "true",
    });
    this.getClassifyList();
  }

  async getClassifyList() {
    const res = await apiGetGoodsClassifyTree();
    if (res.code === 0) {
      this.setState({
        classifyList: res.data.map((v) => {
          return {
            value: v.value,
            label: v.label,
            children: v.children.length > 0 ? v.children : [],
          };
        }),
      });
      // this.getBrandList(this.state.brandClassifyIds);
      this.getBrandList(this.state.brandClassifyIds);
    }
  }
  classifyChange = (e) => {
    this.getBrandList(e[e.length - 1]);
  };
  handleCancel = () => {
    this.setState({
      isModalOpen: false,
      brandList: [],
    });
  };
  brandChange(e) {
    this.setState({
      brandId: e.value,
    });
    const { brandList } = this.state;
    this.setState({
      brandInfo: brandList.find((item) => item.value === e),
      brandName: brandList.find((item) => item.value === e).label,
    });
  }
  async getBrandList(e) {
    // let res = await apiGetBrandinfoList({ brandClassifyId: e });
    let res = await apiGetBrandinfoList();
    // this.setState({
    //   brandName: "",
    // });
    if (res.code === 0) {
      if (this.flag == 1) {
        this.formRef.setFieldsValue({
          brandId: "",
        });
      }
      this.flag = 1;
      console.log(res.data);
      res.data.map((item) => {
        this.setState({
          brandList: [...this.state.brandList, {
            value: item.brandId,
            label: item.brandName,
            brandImg: item.brandImg
          }],
        })
      })
      this.setState({
        // brandList: res.data,
        brandName:
          res.data.find(
            (params) => params.brandId === this.state.brandId
          )
            ? res.data.find((params) => params.brandId === this.state.brandId)
              .brandName
            : "",
      });
      console.log(this.state.brandName);
    }
  }
  getData = async (e) => {
    let res = await apiGetAppBrandInfoView({
      appBrandId: e,
    });
    if (res.code === 0 && res.data) {
      this.formRef.setFieldsValue({
        ...res.data,
        brandId: res.data.brandId,
        brandBanner: res.data.brandBanner,
        // brandClassifyId: res.data.brandClassifyId.split(","),
      });
      // let brandClassifyIdArr = res.data.brandClassifyId.split(",");
      this.setState({
        brandName: res.data.brandName,
        brandId: res.data.brandId,
        // brandClassifyIds: brandClassifyIdArr[brandClassifyIdArr.length - 1],
      });
      let arr = [];
      res.data.appBrandGoods.map((item) => {
        arr.push(item.goodsInfo);
      });
      this.setState({
        brandInfo: {
          brandImg: res.data.brandImg,
        },
        fileList: [
          {
            uid: new Date().getTime(),
            name: "image",
            status: "done",
            url: res.data.brandBanner,
          },
        ],
        dataSource: arr,
      });
    }
  };
  //form表单确定事件
  onFinish = async (values) => {
    console.log(values);
    values.brandImg = this.state.brandInfo.brandImg;
    if (values.appBrandGoods.length < 2) {
      return message.error("请至少选择2个品牌商品用于在品牌专区中展示");
    }
    // values.brandClassifyId = values.brandClassifyId.join(",");
    if (this.state.AdID == 0) {
      // 添加
      let res = await apiGetAppBrandInfoAdd({
        ...values,
        brandName: this.state.brandName,
      });
      if (res.code === 0) {
        React.$message({
          type: "info",
          content: "添加成功",
        });
        this.props.history.goBack();
      } else {
        this.setState({ btnLoading: false });
      }
    } else {
      // 编辑
      let res = await apiGetAppBrandInfoUpdate({
        ...values,
        brandName: this.state.brandName,
        appBrandId: this.state.AdID,
      });
      if (res.code === 0) {
        React.$message({
          type: "info",
          content: "编辑成功",
        });
        this.props.history.goBack();
      } else {
        this.setState({ btnLoading: false });
      }
    }
  };

  // 图片上传回调;
  getDetailsFileResult = (value) => {
    if (value && value.length) {
      let arr = value
        .map((v) => {
          if (v.response && v.response.code === 0) {
            return v.response.data;
          } else {
            return v.url;
          }
        })
        .join(",");
      this.formRef.setFieldsValue({
        brandBanner: arr,
      });
    } else {
      this.formRef.setFieldsValue({
        brandBanner: "",
      });
    }
  };
  chooseShop = () => {
    this.setState({
      isModalOpen: true,
    });
  };
  handleOk = () => {
    let arr = [];
    Object.values(this.TheList.data()).forEach((value) => {
      arr.push(...value);
    });
    const c = this.state.dataSource.concat(arr);

    const d = [...new Set(c.map((t) => JSON.stringify(t)))].map((s) =>
      JSON.parse(s)
    );
    this.setState({
      dataSource: d,
      isModalOpen: false,
    });
    this.formRef.setFieldsValue({
      appBrandGoods: d,
    });
  };
  render() {
    let {
      brandList,
      initialValues,
      isEdit,
      btnLoading,
      AdID,
      classifyList,
      brandInfo,
      isModalOpen,
      title,
      columns,
      dataSource,
      fileList,
      maxSize,
      fileType,
      brandName,
    } = this.state;
    return (
      <div className="commodity-list-detail p-layout-box">
        <GoBack
          history={this.props.history}
          title={AdID == 0 ? "新增品牌" : "编辑品牌"}
        />
        <Modal
          closable={true}
          width={1500}
          title={title}
          destroyOnClose={true}
          visible={isModalOpen}
          onOk={() => this.handleOk()}
          onCancel={() => this.handleCancel()}
        >
          <TheList ref={(ref) => (this.TheList = ref)}></TheList>
        </Modal>
        <div className="p-layout-content">
          <Form
            onFinish={this.onFinish}
            ref={(ref) => (this.formRef = ref)}
            labelCol={{
              span: 4,
            }}
            wrapperCol={{
              span: 5,
            }}
            initialValues={initialValues}
            labelWrap
          >
            {/* <Form.Item
              name="brandClassifyId"
              label={"类目"}
              rules={[{ required: true }]}
            >
              <Cascader
                allowClear={false}
                disabled={isEdit}
                options={classifyList}
                onChange={this.classifyChange}
                placeholder="请选择商品类目"
              />
            </Form.Item> */}
            <Form.Item
              name="brandId"
              label={"品牌名称"}
              rules={[{ required: true }]}
            >
              <Select
                showSearch
                disabled={isEdit}
                options={brandList}
                onChange={(e) => {
                  this.brandChange(e);
                }}
                filterOption={(input, option) =>
                  (option?.label ?? '').toLowerCase().includes(input.toLowerCase())
                }
              >
                {/* {brandList.length > 0
                  ? brandList.map((item) => {
                    return (
                      <Option key={item.brandId} value={item.brandId}>
                        {item.brandName}
                      </Option>
                    );
                  })
                  : brandName} */}
              </Select>
            </Form.Item>
            <Form.Item
              noStyle
              shouldUpdate={(prevValues, currentValues) =>
                prevValues.brandId !== currentValues.brandId
              }
            >
              {({ getFieldValue }) => {
                return getFieldValue("brandId") ? (
                  <Form.Item name="brandImg" label="品牌图片">
                    <Image
                      width={100}
                      height={100}
                      src={brandInfo.brandImg}
                      fallback=""
                    />
                  </Form.Item>
                ) : null;
              }}
            </Form.Item>
            <Form.Item
              name="sorted"
              label={"排序"}
              rules={[{ required: true }]}
            >
              <InputNumber min={1} />
            </Form.Item>
            <Form.Item
              label="大牌专区banner图"
              // extra={`建议尺寸为710 X 250`}
              name="brandBanner"
              rules={[{ required: true }]}
            >
              <TheUpload
                // accept={["image/jpg", "image/jpeg","image/png"]}
                {...fileType}
                maxSize={10}
                // {...maxSize}
                // imgWidth={750}
                // imgHeight={210}
                fileList={fileList}
                getFileResult={this.getDetailsFileResult}
                len={1}
              />
            </Form.Item>
            <Form.Item
              name="appBrandGoods"
              extra={`请至少选择2个品牌商品用于在品牌专区中展示`}
              label={"展示商品"}
              labelWrap={true}
              rules={[{ required: true }]}
            >
              <Button onClick={() => this.chooseShop()}>选择商品</Button>
            </Form.Item>
            {dataSource.length > 0 && (
              <TheTable
                scroll={{ x: "max-content", y: "43vh" }}
                columns={columns}
                dataSource={dataSource}
                style={{ marginBottom: "30px" }}
              />
            )}
            <Form.Item
              wrapperCol={{
                offset: 4,
                span: 16,
              }}
            >
              <Space>
                <Button htmlType="submit" type="primary">
                  保存
                </Button>
              </Space>
            </Form.Item>
          </Form>
        </div>
      </div>
    );
  }
}

export default Edit;
